"""
模板工具 - 基于Linus设计哲学
"分离关注点，不要在Python中写HTML"
"""

import os
from typing import Dict, Any, Optional
from gua import respond


class TemplateRenderer:
    """Linus式模板渲染器 - 简单、实用、无魔法"""
    
    def __init__(self, template_dir: str = "examples/templates"):
        self.template_dir = template_dir
    
    def render(self, template_name: str, context: Optional[Dict[str, Any]] = None) -> str:
        """渲染模板 - 简单的字符串替换，无复杂逻辑"""
        template_path = os.path.join(self.template_dir, template_name)
        
        try:
            with open(template_path, "r", encoding="utf-8") as f:
                content = f.read()
        except FileNotFoundError:
            return f"模板文件不存在: {template_path}"
        
        # 简单的变量替换
        if context:
            for key, value in context.items():
                placeholder = f"{{{{ {key} }}}}"
                content = content.replace(placeholder, str(value))
        
        return content
    
    def respond(self, template_name: str, context: Optional[Dict[str, Any]] = None):
        """返回响应对象"""
        return respond(self.render(template_name, context))


# 全局实例
template = TemplateRenderer()


def render_template(template_name: str, context: Optional[Dict[str, Any]] = None) -> str:
    """便捷函数：渲染模板"""
    return template.render(template_name, context)


def respond_template(template_name: str, context: Optional[Dict[str, Any]] = None):
    """便捷函数：返回模板响应"""
    return template.respond(template_name, context)